package com.carl.guli.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.carl.guli.api.filter.ApiFilter;
import com.carl.guli.common.constant.Constant;
import com.carl.guli.common.exception.BusinessException;
import com.carl.guli.common.util.HttpUtil;
import com.carl.guli.dto.Result;
import com.carl.guli.mapper.*;
import com.carl.guli.model.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * Created by youzm on 2017/5/10.
 */
@Controller
@RequestMapping("/")
public class ApiController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);


    @Autowired
    private ScenicSpotMapper scenicSpotMapper;

    @Autowired
    private FarmStayMapper farmStayMapper;

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private BannerMapper bannerMapper;

    @Autowired
    private HotelMapper hotelMapper;

    @Autowired
    private FeedbackMapper feedbackMapper;

    @Autowired
    private NewsMapper newsMapper;

    //    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping("/scenicSpot/list.do")
    @ResponseBody
    public List<ScenicSpot> getScenicSpotList() {
        ScenicSpotExample example = new ScenicSpotExample();
        example.setOrderByClause("sort desc");
        List<ScenicSpot> scenicSpots = scenicSpotMapper.selectByExample(example);
        return scenicSpots;
    }

    @RequestMapping(value = "/scenicSpot/text/{spotId}.do")
    @ResponseBody
    public ScenicSpot getScenicSpotText(@PathVariable("spotId") Integer spotId) {
        ScenicSpot scenicSpot = scenicSpotMapper.selectByPrimaryKey(spotId);
        return scenicSpot;
    }

    @RequestMapping("/farmStay/list.do")
    @ResponseBody
    public List<FarmStay> getFarmStayList(String location) {
        logger.debug("[ApiController] getFarmStayList begin....");
        List<FarmStay> farmStays = farmStayMapper.selectByExample(null);

        if (location != null && location.split(",").length == 2) {
            try {
                System.out.println("youzm-test:" + location);
                getDistance(location, farmStays);
                sortFarmStayByDistance(farmStays);
            } catch (Exception e) {
                e.printStackTrace();
                return farmStays;
            }

        }

        return farmStays;
    }

    private void sortFarmStayByDistance(List<FarmStay> farmStays) {
//        Comparator<? super FarmStay> mc;
        Comparator<FarmStay> comparator = new Comparator<FarmStay>() {
            @Override
            public int compare(FarmStay o1, FarmStay o2) {
                if (o1.getDistanceNum() == null) return 1;
                if (o2.getDistanceNum() == null) return -1;
                return o1.getDistanceNum() - o2.getDistanceNum();
            }
        };

        Collections.sort(farmStays, comparator) ;
    }

    public void getDistance(String from, List<FarmStay> farmStays) {
        StringBuffer sb = new StringBuffer("");
        for (FarmStay farmStay : farmStays) {
            if (!StringUtils.isEmpty(farmStay.getLocation())) {
                sb.append(farmStay.getLocation() + ";");
            }
        }
        String to = sb.substring(0, sb.length() - 1);
        String url = "http://apis.map.qq.com/ws/distance/v1/?mode=driving&from=" + from + "&to=" + to + "&key=OPOBZ-CTIR6-2EMSP-E5SPU-QQPAJ-2QBJD";
        String returnJson = HttpUtil.httpGet(url);
        if (!StringUtils.isEmpty(returnJson)) {
            JSONObject jsonObject = JSONObject.parseObject(returnJson);
            Integer status = jsonObject.getInteger("status");
            if (status == 373) {
                for (FarmStay farmStay : farmStays) {
                    farmStay.setDistance(">10km");
                    farmStay.setDistanceNum(10000);
                }
                return;
            }
            if (status != 0) {
                for (FarmStay farmStay : farmStays) {
                    farmStay.setDistance("");
                    farmStay.setDistanceNum(10000);
                }
                return;
            }
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray elements = result.getJSONArray("elements");
            for (int i = 0; i < elements.size(); i++) {
                JSONObject jsonObject1 = elements.getJSONObject(i);
                Integer distance = jsonObject1.getInteger("distance");
                farmStays.get(i).setDistanceNum(distance);
                farmStays.get(i).setDistance(convertDistance(distance));
            }
        }
        //排序
    }

    private String convertDistance(Integer distance) {
        if (StringUtils.isEmpty(distance) || -1 == distance) {
            return "";
        }
        if (distance > 1000) {
            BigDecimal bigDecimal = new BigDecimal(distance);
            BigDecimal divide = bigDecimal.divide(new BigDecimal(1000), 1, RoundingMode.HALF_UP);
            return divide.toString() + "km";
        } else {
            return distance + "m";
        }
    }

    @RequestMapping("/farmStay/detail/{farmId}.do")
    @ResponseBody
    public FarmStay getFarmStayDetail(@PathVariable("farmId") Integer farmId) {
        FarmStay farmStays = farmStayMapper.selectByPrimaryKey(farmId);
        List<String> list = new ArrayList<String>();
        farmStays.setBannerList(list);
        if (!StringUtils.isEmpty(farmStays.getBanner1())) {
            list.add(farmStays.getBanner1());
        }
        if (!StringUtils.isEmpty(farmStays.getBanner2())) {
            list.add(farmStays.getBanner2());
        }
        if (!StringUtils.isEmpty(farmStays.getBanner3())) {
            list.add(farmStays.getBanner3());
        }
        if (!StringUtils.isEmpty(farmStays.getBanner4())) {
            list.add(farmStays.getBanner4());
        }
        if (!StringUtils.isEmpty(farmStays.getBanner5())) {
            list.add(farmStays.getBanner5());
        }
        return farmStays;
    }

    @RequestMapping("/farmStay/search.do")
    @ResponseBody
    public Map<String, List> searchFarmStay(String context) {
        FarmStayExample example = new FarmStayExample();
        example.createCriteria().andNameLike("%" + context + "%");
        List<FarmStay> farmStays = farmStayMapper.selectByExample(example);

        GoodExample example1 = new GoodExample();
        example1.createCriteria().andNameLike("%" + context + "%");
        List<Good> goods = goodMapper.selectByExample(example1);

        Map<String, List> map = new HashMap<String, List>();
        map.put("farmStays", farmStays);
        map.put("goods", goods);
        return map;
    }


    @RequestMapping("/good/list.do")
    @ResponseBody
    public List<Good> getGoodList() {
        GoodExample example = new GoodExample();
        example.setOrderByClause("sort desc");
        List<Good> goods = goodMapper.selectByExample(example);
        return goods;
    }

    @RequestMapping("/good/detail/{goodId}.do")
    @ResponseBody
    public Good getGoodDetail(@PathVariable("goodId") Integer goodId) {
        Good good = goodMapper.selectByPrimaryKey(goodId);
        List<String> list = new ArrayList<String>();
        good.setBannerList(list);
        if (!StringUtils.isEmpty(good.getBanner1())) {
            list.add(good.getBanner1());
        }
        if (!StringUtils.isEmpty(good.getBanner2())) {
            list.add(good.getBanner2());
        }
        if (!StringUtils.isEmpty(good.getBanner3())) {
            list.add(good.getBanner3());
        }
        if (!StringUtils.isEmpty(good.getBanner4())) {
            list.add(good.getBanner4());
        }
        if (!StringUtils.isEmpty(good.getBanner5())) {
            list.add(good.getBanner5());
        }
        return good;
    }

    @RequestMapping("/banner/list.do")
    @ResponseBody
    public List<Banner> getBannerList(HttpServletResponse httpServletResponse) {
        logger.debug("[ApiController] getBannerList begin....");
        BannerExample example = new BannerExample();
        example.setOrderByClause("sort desc");
        List<Banner> banners = bannerMapper.selectByExample(example);
        return banners;
    }

    @RequestMapping("/hotel/list.do")
    @ResponseBody
    public List<Hotel> getHotelList(String location) {
        List<Hotel> hotels = hotelMapper.selectByExample(null);
        if (location != null) {
            try {
                getDistanceForHotel(location, hotels);
                sortHotelsByDistance(hotels);
            } catch (Exception e) {
                e.printStackTrace();
                return hotels;
            }

        }
        return hotels;
    }

    @RequestMapping("/hotel/search.do")
    @ResponseBody
    public List<Hotel> seachHotelList(String context, String location) {
        HotelExample example = new HotelExample();
        if (!StringUtils.isEmpty(context)) {
            example.createCriteria().andNameLike("%" + context + "%");
        }
        List<Hotel> hotels = hotelMapper.selectByExample(example);
        if (location != null) {
            try {
                getDistanceForHotel(location, hotels);
                sortHotelsByDistance(hotels);
            } catch (Exception e) {
                e.printStackTrace();
                return hotels;
            }
        }
        return hotels;
    }

    private void sortHotelsByDistance(List<Hotel> hotels) {
        Comparator<Hotel> comparator1 = new Comparator<Hotel>() {
            @Override
            public int compare(Hotel o1, Hotel o2) {
                if (o1.getDistanceNum() == null) return 1;
                if (o2.getDistanceNum() == null) return -1;
                return o1.getDistanceNum() - o2.getDistanceNum();
            }
        };

        Collections.sort(hotels, comparator1) ;
    }

    @RequestMapping("/hotel/detail/{hotelId}.do")
    @ResponseBody
    public Hotel getHotelDetail(@PathVariable("hotelId") Integer hotelId) {
        Hotel hotel = hotelMapper.selectByPrimaryKey(hotelId);
        List<String> list = new ArrayList<String>();
        hotel.setBannerList(list);
        if (!StringUtils.isEmpty(hotel.getBanner1())) {
            list.add(hotel.getBanner1());
        }
        if (!StringUtils.isEmpty(hotel.getBanner2())) {
            list.add(hotel.getBanner2());
        }
        if (!StringUtils.isEmpty(hotel.getBanner3())) {
            list.add(hotel.getBanner3());
        }
        return hotel;
    }

    private void getDistanceForHotel(String location, List<Hotel> hotels) {
        StringBuffer sb = new StringBuffer("");
        for (Hotel hotel : hotels) {
            if (!StringUtils.isEmpty(hotel.getLocation())) {
                sb.append(hotel.getLocation() + ";");
            }
        }
        String to = sb.substring(0, sb.length() - 1);
        String url = "http://apis.map.qq.com/ws/distance/v1/?mode=driving&from=" + location + "&to=" + to + "&key=OPOBZ-CTIR6-2EMSP-E5SPU-QQPAJ-2QBJD";
        String returnJson = HttpUtil.httpGet(url);
        System.out.println("youzmtest---" + returnJson);
        if (!StringUtils.isEmpty(returnJson)) {
            JSONObject jsonObject = JSONObject.parseObject(returnJson);
            Integer status = jsonObject.getInteger("status");
            if (status == 373) {
                for (Hotel hotel : hotels) {
                    hotel.setDistance(">10km");
                    hotel.setDistanceNum(10000);
                }
                return;
            }
            if (status != 0) {
                for (Hotel hotel : hotels) {
                    hotel.setDistance("");
                    hotel.setDistanceNum(10000);
                }
                return;
            }
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray elements = result.getJSONArray("elements");
            for (int i = 0; i < elements.size(); i++) {
                JSONObject jsonObject1 = elements.getJSONObject(i);
                Integer distance = jsonObject1.getInteger("distance");
                hotels.get(i).setDistance(convertDistance(distance));
                hotels.get(i).setDistanceNum(distance);
            }
        }
    }

    @RequestMapping("/feedback/add.do")
    @ResponseBody
    public Result feedback(FeedbackWithBLOBs feed) {
        if (StringUtils.isEmpty(feed.getPhone()) || feed.getPhone().length() != 11) {
            throw new BusinessException("您输入的不是正确的手机号码");
        }

        if (StringUtils.isEmpty(feed.getText())) {
            throw new BusinessException("反馈内容不能为空");
        }


        int i = feedbackMapper.insertSelective(feed);
        return new Result(1, "");

    }

    @RequestMapping("/news/list.do")
    @ResponseBody
    public PageInfo<News> getNewsList(News news) {
        PageHelper.startPage(news.getPage().getPageNum(), news.getPage().getPageSize());
        NewsExample example = new NewsExample();
        example.setOrderByClause("publish_time desc, create_time desc");
        List<News> newses = newsMapper.selectByExample(example);

        PageInfo<News> pageInfo = new PageInfo(newses);
        return pageInfo;
    }

    @RequestMapping(value = "/news/text/{newsId}.do")
    @ResponseBody
    public News getNewsText(@PathVariable("newsId") Integer newsId) {
        News news = newsMapper.selectByPrimaryKey(newsId);
        return news;
    }
}
